/** * 创建异步请求对象xmlHttpRequest (兼容各个版本浏览器) * @return {*} */
function createXMLHttpRequest() {
    let xmlHttp;
    // 适用于大多数浏览器，以及IE7和IE更高版本
     try {
         xmlHttp = new XMLHttpRequest();
         // 前端设置是否带cookie
         xmlHttp.withCredentials = true;
     } catch (e) {
         // 适用于IE6
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            // 适用于IE5.5，以及IE更早版本
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {

            }
        }
     }
     return xmlHttp;
}

/**
 * 异步请求JSON数据
 * @param serverAddress
 * @param url
 * @param data
 * @param timeout
 * @param requestBefore
 * @param requestAfter
 * @returns {Promise<unknown>}
 */
const POST = function ({serverAddress, url, data, timeout = 10000, requestBefore, requestAfter}) {
    return new Promise(function (resolve, reject) {
        // 超时将强制abort,直接退出
        const timeoutHandle = setTimeout(function () {
            if (XMLHttpRequest.readyState !== 4) {
                reject(new Error('connect network timeout!'));
                XMLHttpRequest.abort();
            }
        }, timeout);

        // readyState changed
        const onReadyStateChangeHandler = function () {
            if (this.readyState !== 4) {
                return;
            }
            // 清除超时定时器
            clearTimeout(timeoutHandle);

                // 响应码200
            if (this.status === 200) {
                const respPlainText = this.response;
                resolve(respPlainText);
            } else {
                reject(new Error(this.statusText));
            }
        };
        // 创建xhr
        const XMLHttpRequest = new createXMLHttpRequest();

        // 请求前回调
        typeof requestBefore === 'function' && requestBefore();
        XMLHttpRequest.open("POST", serverAddress + url);
        XMLHttpRequest.timeout = 1000;
        XMLHttpRequest.onreadystatechange = onReadyStateChangeHandler;
        XMLHttpRequest.responseType = "json";
        XMLHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        XMLHttpRequest.send(data);
        typeof requestAfter === 'function' && requestAfter();
    });
};

/**
 * get 请求
 * @param serverAddress
 * @param url
 * @param data
 * @param timeout
 * @param requestBefore
 * @param requestAfter
 * @returns {Promise<unknown>}
 * @constructor
 */
const GET = function ({serverAddress, url, data, timeout = 10000, requestBefore, requestAfter}) {
    return new Promise(function (resolve, reject) {
        // readyState changed
        const onReadyStateChangeHandler = function () {
            console.log('get 请求timeoutHandle' )

            if (this.readyState !== 4) {
                return;
            }console.log('get 请求response: ' + this.response)
            // 清除超时定时器
            clearTimeout(timeoutHandle);
            // 响应码200
            if (this.status === 200) {
                const respPlainText = this.response;
                resolve(respPlainText);
            } else {
                reject(new Error(this.statusText));
            }
        };
        // 创建xhr
        const XMLHttpRequest = new createXMLHttpRequest();
        // 超时将强制abort,直接退出
        const timeoutHandle = setTimeout(function () {
            if (XMLHttpRequest.readyState !== 4) {
                reject(new Error('connect network timeout!'));
                XMLHttpRequest.abort();
            }
        }, timeout);
        // json 转urldata
        const dataBody = Object.keys(data).map(function (key) {
            return encodeURIComponent(key) + "=" + encodeURIComponent(data[key]);
        }).join("&");
        // 请求前回调
        typeof requestBefore === 'function' && requestBefore();
        XMLHttpRequest.open("GET", serverAddress + url + '?' + dataBody, true);
        XMLHttpRequest.timeout = 1000;
        XMLHttpRequest.onreadystatechange = onReadyStateChangeHandler;
        XMLHttpRequest.send(null);
        typeof requestAfter === 'function' && requestAfter();
    });
};

export {POST, GET}